<!-- 基础商品 -->
<!-- 基础商品 -->
<template>
  <el-dialog v-model="dialogVisible" width="450" title="基础商品" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <el-form ref="elFormRef" v-auto-animate :model="formData" :rules="rules" scrollToError>
      <el-form-item label="商品名称" labelWidth="6em" prop="productName">
        <el-input v-model="formData.productName" :maxlength="12" clearable placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品类型" labelWidth="6em" prop="productType">
        <box-from-border>
          <el-radio-group v-model="formData.productType">
            <el-radio label="充值K币" :value="1"></el-radio>
            <el-radio label="充值会员" :value="2"></el-radio>
            <el-radio label="全集解锁" :value="4"></el-radio>
          </el-radio-group>
        </box-from-border>
      </el-form-item>
      <el-form-item label="商品价格" labelWidth="6em" prop="productPrice">
        <el-select-v2
          v-model="formData.productPrice"
          :props="{ label: 'val', value: 'val' }"
          :options="priceInfo.priceList || []"
          filterable
          :persistent="false"
          placeholder="请选择商品价格"
        ></el-select-v2>
      </el-form-item>
      <el-form-item v-if="formData.productType === 1" label="K币数量" labelWidth="6em" prop="diamondQuantity">
        <base-input-number v-model="formData.diamondQuantity" verify="all_int" disabled clearable placeholder="请输入K币数量"></base-input-number>
      </el-form-item>
      <el-form-item v-if="formData.productType === 2" key="el-form-item-2" label="会员天数" labelWidth="6em" prop="vipDays">
        <base-input-number v-model="formData.vipDays" verify="all_int" clearable placeholder="请输入会员天数"></base-input-number>
      </el-form-item>
      <el-form-item labelWidth="0em">
        <div style="width: 100%; padding-top: 20px">
          <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormItemRule, FormRules } from 'element-plus';
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import { type AddBaseProductRequest, type BaseProduct, type ProductPriceInfo, addBaseProductAxios, editBaseProductAxios } from '@/api/product-management';

  type $EditShowData = {
    /** 操作 */
    action: 'edit';
    /** 价格信息 */
    priceInfo: ProductPriceInfo;
    /** 商品信息 */
    baseProduct: BaseProduct;
    /** 审核后的回调 */
    editCallBack?: () => void;
  };

  type $AddShowData = {
    /** 操作 */
    action: 'add';
    /** 价格信息 */
    priceInfo: ProductPriceInfo;
    /** 审核后的回调 */
    addCallBack?: () => void;
  };
  type $ShowData = $AddShowData | $EditShowData;
  type FormData = Pick<AddBaseProductRequest, 'productName' | 'productPrice' | 'productType'> & {
    /** K币数量 */
    diamondQuantity: number | null;
    /** 会员天数 */
    vipDays: number | null;
  };

  let addCallBack: $AddShowData['addCallBack'] = undefined;
  let editCallBack: $EditShowData['editCallBack'] = undefined;
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const loading = ref(false);
  const action = ref<'add' | 'edit'>();
  const productId = ref<number>(-1);
  const priceInfo = shallowRef<ProductPriceInfo>({ priceList: [], priceRate: -1 });

  const formData = reactive<FormData>({
    productName: '',
    productPrice: null,
    diamondQuantity: null,
    vipDays: null,
    productType: 1,
  });

  watch(
    () => formData.productPrice,
    (price) => {
      formData.diamondQuantity = typeof price === 'number' ? price * priceInfo.value.priceRate! : null;
    }
  );
  const rules = computed(() => {
    const _rules: FormRules<FormData> = {
      productName: [{ required: true, type: 'string', message: '请输入商品名称', trigger: ['blur', 'change'] }],
      productPrice: [
        { required: true, type: 'number', message: '请输入商品价格', trigger: ['blur', 'change'] },
        { required: true, min: 0.01, type: 'number', message: '请输入商品价格', trigger: ['blur', 'change'] },
      ],
      productType: [
        { required: true, type: 'number', message: '请选择商品类型', trigger: ['blur', 'change'] },
        { type: 'enum', enum: [1, 2, 4], message: `商品类型不合法`, trigger: ['blur', 'change'] },
      ],
    };

    if (formData.productType === 1) {
      _rules.diamondQuantity = [
        { required: true, type: 'number', message: '请输入K币数量', trigger: ['blur', 'change'] },
        { required: true, min: 1, type: 'integer', message: 'K币数量不合法', trigger: ['blur', 'change'] },
      ] satisfies FormItemRule[];
    } else if (formData.productType === 2) {
      _rules.vipDays = [
        { required: true, type: 'number', message: '请开通会员天数', trigger: ['blur', 'change'] },
        { required: true, min: 1, type: 'integer', message: '会员天数不合法', trigger: ['blur', 'change'] },
      ] satisfies FormItemRule[];
    }

    return _rules;
  });

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        const data: AddBaseProductRequest = {
          productName: formData.productName,
          productPrice: formData.productPrice,
          productQuantity: formData.productType === 1 ? formData.diamondQuantity : formData.productType === 2 ? formData.vipDays : 1,
          productType: formData.productType,
        };

        if (action.value === 'edit') {
          const edetData = { ...data, productId: productId.value! };
          await editBaseProductAxios(edetData);
          typeof editCallBack === 'function' && editCallBack();
        } else {
          await addBaseProductAxios(data);
          typeof addCallBack === 'function' && addCallBack();
        }

        loading.value = false;
        hide();
      } catch (error) {
        loading.value = false;
        ElToast.error(error.msg || '提交失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  function show(data: $ShowData) {
    action.value = data.action;
    priceInfo.value = data.priceInfo;
    if (data.action === 'edit') {
      productId.value = data.baseProduct.productId;
      formData.productName = data.baseProduct.productName ?? '';
      formData.productPrice = data.baseProduct.productPrice ?? null;
      formData.productType = data.baseProduct.productType ?? 1;
      formData.diamondQuantity = null;
      formData.vipDays = null;
      if (formData.productType === 1) {
        formData.diamondQuantity = data.baseProduct.productQuantity ?? null;
      } else if (formData.productType === 2) {
        formData.vipDays = data.baseProduct.productQuantity ?? null;
      }
    } else {
      formData.productName = '';
      formData.productPrice = null;
      formData.diamondQuantity = null;
      formData.vipDays = null;
      formData.productType = 1;
    }

    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;

    dialogVisible.value = true;
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  defineExpose({ show, hide });
</script>
